package com.wyzz.hr.util;

import com.wyzz.hr.base.quartz.DatabaseBackupService;
import com.wyzz.hr.bo.TemplateService;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.*;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;

public class Environment implements ServletContextListener {

	public enum SystemVariables {
		FILE_SEPARATOR, APPLICATION_HOME, TEMPLATE_HOME, PAGE_SIZE, CUSTOMER_FILE_HOME, PDF_TEMPLATE_HOME;
	}

	public Environment() {
		config = PropertiesFileConfigManager.getInstance();
	}

	public static String getFileSeparator() {
		return (String) sysMap.get(SystemVariables.FILE_SEPARATOR);
	}

	public static String getEmailTemplateHome() {
		return (String) sysMap.get(SystemVariables.TEMPLATE_HOME);
	}

	public static String getPDFTemplateHome() {
		return (String) sysMap.get(SystemVariables.PDF_TEMPLATE_HOME);
	}

	public static String getResourceHome() {
		String appHome = (String) sysMap.get(SystemVariables.APPLICATION_HOME);
		String imagesHome = (new StringBuilder()).append(appHome).append(
				"resource").append(getFileSeparator()).toString();
		return imagesHome;
	}

	public static String getApplicationHome() {
		return (String) sysMap.get(SystemVariables.APPLICATION_HOME);
	}

	public static String getClassRootPath() {
		String appHome = getApplicationHome();
		return (new StringBuilder()).append(appHome).append(getFileSeparator())
				.append("WEB-INF").append(getFileSeparator()).append("classes")
				.append(getFileSeparator()).toString();
	}

	public static String getFileHome() {
		return (String) sysMap.get(SystemVariables.CUSTOMER_FILE_HOME);
	}

	public void contextDestroyed(ServletContextEvent servletcontextevent) {
	}

	public void contextInitialized(ServletContextEvent contextEvent) {
		application = contextEvent.getServletContext();
		doInit();
	}

	private void doInit() {
		sysMap.put(SystemVariables.FILE_SEPARATOR, SystemUtils.FILE_SEPARATOR);
		logger.info("wyzzhrms100\u7CFB\u7EDF\u521D\u59CB\u5316\u5F00\u59CB..."); // wyzzhrms100系统初始化开始
		//...
		Map props = config.getProperties();
		String path = application.getRealPath("");
		System.out.println(path);
		String filePath = (new File(path)).getParentFile().getAbsolutePath();
		System.out.println(filePath);
		String readPath = StringUtils.defaultIfEmpty((String) props
				.get("sys.file.path"), "file/");
		readPath = (new StringBuilder()).append("/").append(readPath)
				.toString();
		logger
				.info((new StringBuilder())
						.append(
								"\u7528\u6237\u6587\u4EF6\u7684\u5B8C\u6574\u5B58\u653E\u8DEF\u5F84\u4E3A\uFF1A")// 用户文件的完整存放路径为
						// ：
						.append(filePath).append(readPath).toString());
		File file = new File((new StringBuilder()).append(filePath).append(
				readPath).toString());
		if (!file.exists())
			file.mkdirs();
		sysMap.put(SystemVariables.CUSTOMER_FILE_HOME, (new StringBuilder())
				.append(path).append(readPath).toString());
		sysMap.put(SystemVariables.TEMPLATE_HOME, (new StringBuilder()).append(
				path).append("\\WEB-INF\\emailtemplate").append(
				getFileSeparator()).toString());
		String applicationHome = application.getRealPath("/");
		System.out.println(applicationHome);
		sysMap.put(SystemVariables.APPLICATION_HOME, applicationHome);
		logger.info((new StringBuilder()).append(
				"web\u5B8C\u6574\u5B58\u653E\u8DEF\u5F84\u4E3A\uFF1A").append(
				applicationHome).toString());// web完整存放路径为：
		sysMap.put(SystemVariables.PDF_TEMPLATE_HOME, (new StringBuilder())
				.append(path).append("\\WEB-INF\\pdftemplate").append(
						getFileSeparator()).toString());
		// doBackupDatabase((new StringBuilder()).append(filePath)
		// .append(readPath).toString());
		// doCopyFtlTemplate("emailtemplate");
		// doCopyFtlTemplate("pdftemplate");
		logger.info("WYZZHRMS100\u7CFB\u7EDF\u521D\u59CB\u5316\u7ED3\u675F");// 系统初始化结束
	}

	private void doCopyFtlTemplate(String templateType) {
		String fromFolder = (new StringBuilder()).append(getApplicationHome())
				.append("WEB-INF").append(getFileSeparator()).append(
						templateType).append(getFileSeparator()).toString();
		String toFolder = (new StringBuilder()).append(getFileHome()).append(
				templateType).append(getFileSeparator()).toString();
		TemplateService templateService = (TemplateService) SpringBeanFactory
				.getBean("ftlTemplateService");
		logger.info((new StringBuilder()).append("Start to copy ").append(
				templateType).append(" from folder ").append(fromFolder)
				.append(" to folder ").append(toFolder).toString());
		templateService.doTemplateCopy(fromFolder, toFolder);
		logger.info((new StringBuilder()).append("End of copy ").append(
				templateType).toString());
	}

	private void doBackupDatabase(String path) {
		DataSource dataSource = (DataSource) SpringBeanFactory
				.getBean("dataSource");
		try {
			dataSource.getConnection().close();
		} catch (SQLException e) {
			logger
					.warn("\u65E0\u6CD5\u8FDE\u63A5\u6570\u636E\u5E93\uFF0C\u8DF3\u8FC7\u6570\u636E\u5907\u4EFD\u3002");// 无法连接数据库
			// ，
			// 跳过数据备份
			// 。
			return;
		}
		String folderPath = (new StringBuilder()).append(path).append(
				config.getProperty("sys.security.backup.path")).toString();
		logger
				.info((new StringBuilder())
						.append(
								"\u6570\u636E\u5907\u4EFD\u5F00\u59CB\uFF0C\u68C0\u67E5\u5907\u4EFD\u76EE\u5F55\uFF1A")// 数据备份开始
						// ，
						// 检查备份目录
						// ：
						.append(folderPath).toString());
		File files = new File(folderPath);
		if (!files.exists())
			files.mkdirs();
		String names[] = files.list();
		Arrays.sort(names);
		String serString = (new SimpleDateFormat("yyyy-MM-dd"))
				.format(new Date());
		for (int i = names.length - 1; i > 0; i--)
			if (StringUtils.contains(names[i], serString)) {
				logger.info((new StringBuilder()).append(serString).append(
						"\u5B58\u5728\u6570\u636E\u5907\u4EFD\u6587\u4EF6")// 存在数据备份文件
						.toString());
				return;
			}
		// DatabaseBackupService service = new DatabaseBackupService();
		// service.executeBackup();
		logger.info("\u6570\u636E\u5E93\u5907\u4EFD\u5B8C\u6BD5");// 数据库备份完毕
	}

	private static Logger logger = Logger.getLogger(Environment.class);
	private static ServletContext application;
	private static Map sysMap = Collections.synchronizedMap(new HashMap());
	SysConfigManager config;
}
